package cn.schoolwow.quickapi.module.business.apiParameter.flow.parameter;

import cn.schoolwow.quickapi.module.business.api.domain.API;
import cn.schoolwow.quickapi.module.business.apiParameter.domain.APIParameter;
import cn.schoolwow.quickapi.module.common.flow.MockDataFlow;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;

import java.lang.reflect.Parameter;

public class GetByRequestBodyAnnotationFlow implements BusinessFlow {
    private Logger logger = LoggerFactory.getLogger(GetByRequestBodyAnnotationFlow.class);

    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        API api = (API) flowContext.checkData("api");
        Parameter parameter = (Parameter) flowContext.checkData("parameter");
        APIParameter apiParameter = (APIParameter) flowContext.checkData("apiParameter");
        StringBuilder requestBodyBuilder = (StringBuilder) flowContext.checkData("requestBodyBuilder");

        RequestBody requestBody = parameter.getAnnotation(RequestBody.class);
        if(null==requestBody){
            return;
        }
        api.contentType = "application/json";
        apiParameter.annotation = requestBody;
        apiParameter.required = requestBody.required();

        flowContext.startFlow(new MockDataFlow())
                .putTemporaryData("clazz", parameter.getType())
                .putTemporaryData("methodName", api.method.getName())
                .execute();
        String jsonString = flowContext.getData("jsonString", String.class);
        if(null!=jsonString){
            requestBodyBuilder.append(jsonString);
        }

        flowContext.brokenCurrentCompositeBusiness("");
    }

    @Override
    public String name() {
        return "通过RequestBody注解获取参数";
    }
}
